import cookieParser from 'cookie-parser';
import express, {
  NextFunction,
  Request,
  Response,
} from 'express';
import session from 'express-session';
import createError from 'http-errors';
import jwt from 'jsonwebtoken';
import logger from 'morgan';
import path from 'path';
import * as rfs from 'rotating-file-stream'; // version 2.x

import { SYSTEM } from './src/config/Config';
import indexRouter from './src/routes/index';
import jwtToken, { lessPaths } from './src/security/jwtToken';

const app = express();

// view engine setup
app.set('views', path.join(__dirname, './src/views'));
app.set('view engine', 'jade');

//系统日志
var accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, './logs/log')
})
app.use(logger(':method :url :status :res[content-length] - :response-time ms', { stream: accessLogStream }));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());


app.use(session({
  secret: SYSTEM.privateKey,
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false }
}))

app.use(express.static(path.join(__dirname, 'public')));


//加登陆的拦截
app.use(/.*/, function (err: any, req: Request, res: Response, next: NextFunction) {
  let less = lessPaths.find(item => {
    return req.url.startsWith(item);
  })
  if (less) {
    next();
    return;
  }
  if (!req.headers.authorization) {
    res.status(401).send({
      code: 401,
      msg: '请先登录！'
    });
  } else {
    jwt.verify(req.headers.authorization.split(" ")[1], SYSTEM.privateKey, (error, decoded) => {
      if (error) {
        res.status(401).send({
          code: 401,
          msg: 'token错误或已过期'
        });
      } else {
        req.headers.user = JSON.stringify(decoded);
        next();
      }
    })
  }
});

//是否登陆的判断
app.use(jwtToken);

//注册路由
app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function (req: Request, res: Response, next: NextFunction) {
  next(createError(404));
});

// error handler
app.use(function (err: any, req: Request, res: Response, next: NextFunction) {
  if (err.name === "UnauthorizedError") {
    res.status(401).send({
      code: 401,
      msg: '请先登录！'
    });
  }
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
console.log('启动成功');

module.exports = app;
